package com.saer.client.form.login;

import com.saer.client.SaerEntryPoint;
import com.saer.client.button.login.CentroMedicoType;
import com.saer.client.combobox.diagnostico.CentroMedico;
import com.saer.client.constants.ClientConstants;
import com.saer.client.dto.login.LoginDto;
import com.saer.client.form.BaseSearchForm;
import com.saer.client.text.login.Password;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.form.fields.CanvasItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.form.fields.events.KeyPressEvent;
import com.smartgwt.client.widgets.form.fields.events.KeyPressHandler;

public class LoginForm extends BaseSearchForm {

	private CanvasItem banner = new CanvasItem();
	private CanvasItem footer = new CanvasItem();
	private CentroMedicoType centroMedicoType = new CentroMedicoType();
	private CentroMedico centroMedico = new CentroMedico();
	private Password password = new Password();

	public LoginForm() {
		this.setSize("100%", "100%");
		this.setGroupTitle("<b>SAER-Web</b>");
		this.setIsGroup(true);
		this.setNumCols(2);
		this.setPadding(10);
		
		banner.setCanvas(new Img("minibanner.png", 250, 125));
		banner.setColSpan(2);
		banner.setShowTitle(false);
		
		footer.setCanvas(new Img("minifooter.png", 250, 100));
		footer.setColSpan(2);
		footer.setShowTitle(false);
		
		centroMedicoType.addChangedHandler(new ChangedHandler() {

			public void onChanged(ChangedEvent event) {
				int value = Integer.valueOf((String) event.getValue());
				if (value == ClientConstants.HOSPITAL) {
					centroMedico.cargarHospitales();
				} else if (value == ClientConstants.CAP) {
					centroMedico.cargarCaps();
				}
			}

		});

		password.addKeyPressHandler(new KeyPressHandler() {

			public void onKeyPress(KeyPressEvent event) {
				if (event.getKeyName().equals("Enter")) {
					SaerEntryPoint.setLogin(getData());
					SaerEntryPoint.loadMainScreen();
				}
			}

		});

		this.setFields(banner, centroMedicoType, centroMedico, password, footer);
	}

	public LoginDto getData() {
		return new LoginDto(
				Integer.valueOf(centroMedico.getValueAsString()),
				centroMedico.getDisplayValue(),
				Integer.valueOf(centroMedicoType.getValueAsString()),
				password.getValueAsString());
	}

}
